package com.qsl.ssyx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qsl.ssyx.acl.service.AdminRoleService;
import com.qsl.ssyx.model.acl.Admin;
import com.qsl.ssyx.acl.mapper.AdminMapper;
import com.qsl.ssyx.acl.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qsl.ssyx.model.acl.AdminRole;
import com.qsl.ssyx.vo.acl.AdminQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 青衫泪
 * @since 2023-08-06
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private AdminRoleService adminRoleServicel;

    //    条件分页查询
    @Override
    public IPage<Admin> selectPage(Page<Admin> pageParam, AdminQueryVo adminQueryVo) {
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(adminQueryVo.getName()) || !StringUtils.isEmpty(adminQueryVo.getUsername())) {
            lqw.like(Admin::getName, adminQueryVo.getUsername().trim())
                    .or().like(Admin::getUsername, adminQueryVo.getUsername().trim());
        }
        lqw.orderByDesc(Admin::getId); //倒序排序

        return baseMapper.selectPage(pageParam, lqw);
    }

    //    为用户分配角色
    @Override
    public Boolean doAssign(Long adminId, Long[] roleIds) {
        // 1.删除用户角色所有已存在的角色
        LambdaQueryWrapper<AdminRole> lqw = new LambdaQueryWrapper<AdminRole>();
        lqw.eq(AdminRole::getAdminId,adminId);
        adminRoleServicel.remove(lqw);

        List<AdminRole> roleList = new ArrayList<>();
        for (Long role : roleIds) {
            AdminRole adminRole = new AdminRole();
            adminRole.setRoleId(role);
            adminRole.setAdminId(adminId);
            roleList.add(adminRole);
        }

        // 2.新增用户角色
        boolean flag = adminRoleServicel.saveBatch(roleList);
        return flag;
    }
}
